﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Common.Utilities;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.FileManipulation
{
    /// <summary>
    /// 
    /// </summary>
    public class FilePathMappingWorker:IWorker 
    {
        #region fields
        private Thread _WorkerThread;
        private FilePathMappingInstruction _Instruction;
        private FilePathMappingOutput _Output;
        private Guid _JobTicketID;
        private RunContext _Context;
        private string _WorkflowName;
        private string _ComponentName;

        /// <summary>
        /// 
        /// </summary>
        public string ComponentName
        {
            get { return _ComponentName; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string WorkflowName
        {
            get { return _WorkflowName; }
        }
        #endregion

        #region IWorker Members

        public Thread WorkerThread
        {
            get { return _WorkerThread; }
        }

        public InstructionBase Instruction
        {
            get { return _Instruction; }
        }

        public ResultBase Output
        {
            get { return _Output; }
        }

        public Type ComponentType
        {
            get { return typeof(FilePathMappingComponent); }
        }

        public RunContext Context
        {
            get { return _Context; }
            set { _Context = value; }
        }

        public void SetInstruction(Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._JobTicketID = ticketGuid;
            this._Instruction = (FilePathMappingInstruction)request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        public void SetInstruction(RunContext context, Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._JobTicketID = ticketGuid;
            this._Instruction = (FilePathMappingInstruction)request;
            this._Context = context;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        public void DoWork()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._JobTicketID, this, this.GetType(), this._Instruction);
            }
            this._WorkerThread = Thread.CurrentThread;
            this.MapFilePaths();
        }


        public void DoWorkAsync()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._JobTicketID, this, this.GetType(), this._Instruction);
            }
            this._WorkerThread = new Thread(new ThreadStart(this.MapFilePaths));
            this._WorkerThread.Start();
        }

        public void CancelWork()
        {
            if (this._WorkerThread != null && this._WorkerThread.IsAlive)
            {
                this._WorkerThread.Abort();
                if (this.WorkerCancelledEvent != null)
                {
                    this.WorkerCancelledEvent(this._JobTicketID, this.GetType(), this._Instruction);
                }
            }

        }

        public event WorkerStarted WorkerStartedEvent;
        public event WorkerFinished WorkerFinishedEvent;
        public event WorkerHasError WorkerErredEvent;
        public event WorkerCancelled WorkerCancelledEvent;
        public event WorkerStatusChanged WorkerStatusChangedEvent;

        #endregion

        #region work
        private void MapFilePaths()
        {
            SqlConnection conn=new SqlConnection(this._Instruction.ConnStr);
            try
            {
                TableColumn idCol = DbUtil.GetTableColumn(
                    DataProviderType.MSSQL, this._Instruction.ConnStr, string.Empty, this._Instruction.TblName,
                    this._Instruction.IDField);
                SqlDbType idDbType = idCol.DbType;
                conn.Open();
                SqlCommand cmd = conn.CreateCommand();
                cmd.CommandType = CommandType.Text;

                DirectoryInfo dirInfo=new DirectoryInfo(this._Instruction.FolderPath);
                FileInfo[] files = null;
                if(this._Instruction.IncludeSubFolders)
                {
                    files = dirInfo.GetFiles(this._Instruction.FileNameSearchPattern, SearchOption.AllDirectories);
                }
                else
                {
                    files = dirInfo.GetFiles(this._Instruction.FileNameSearchPattern, SearchOption.TopDirectoryOnly);
                }

                Regex fileNameRegex=new Regex(this._Instruction.FileNameMatchPattern,RegexOptions.IgnoreCase);
                Match fileNameMatch;
                int fileScanned = 0;
                int fileMapped = 0;
                foreach (FileInfo file in files)
                {
                    string fileName = file.Name;
                    string idValue = fileName;
                    if (!string.IsNullOrEmpty(this._Instruction.FileNameMatchPattern))
                    {
                        fileNameMatch = fileNameRegex.Match(fileName);
                        if (fileNameMatch.Success)
                        {
                            idValue = fileNameMatch.Groups[this._Instruction.CatchIndex].Value;
                        }
                    }

                    string filePath = file.FullName;
                    string sql = string.Format(
                        "update {0} set {1}='{2}' where {3}={4}",
                        this._Instruction.TblName,
                        this._Instruction.FilePathField,
                        filePath,
                        this._Instruction.IDField,
                        FieldDataType.ToMssqlDataValue(idDbType, idValue));
                    cmd.CommandText = sql;
                    cmd.ExecuteNonQuery();

                    fileMapped++;

                    fileScanned++;

                    if (this.WorkerStatusChangedEvent != null && fileScanned%100 == 0)
                    {
                        string msg = string.Format("Scanning {0} of {1} files, {2} file paths mapped",
                                                   fileScanned, files.Length, fileMapped);
                        int pct = fileScanned*100/files.Length;
                        this.WorkerStatusChangedEvent(this._JobTicketID, this.GetType(), this._Instruction, this.WorkflowName, this.ComponentName, msg, pct);
                    }
                }

                this._Output=new FilePathMappingOutput(
                    this._Instruction.OwnerComponentID,this._JobTicketID,fileMapped);

                if(this.WorkerFinishedEvent !=null)
                {
                    this.WorkerFinishedEvent(this._JobTicketID, this.GetType(), this._Instruction, this._Output);
                }
            }
            catch (Exception ex)
            {
                if (this.WorkerErredEvent != null)
                    this.WorkerErredEvent(this._JobTicketID, this.GetType(), this._Instruction, ex.ToString(),true);
            }
            finally
            {
                conn.Close();
            }
        }
        #endregion
    }
}
